YAHOO.namespace("hcm.tally");

var Dom = YAHOO.util.Dom;

function init() {
	/**
	 * 下面是按钮的设置
	 */
	var btn_in = new YAHOO.widget.Button("btn_in");
	var btn_out = new YAHOO.widget.Button("btn_out");
	var btn_access = new YAHOO.widget.Button("btn_access");
	var btn_transfer = new YAHOO.widget.Button("btn_transfer");
	var btn_debt = new YAHOO.widget.Button("btn_debt");

	/**
	 * 金额的格式化函数
	 */
	var formatMoney = function(elCell, oRecord, oColumn, oData) {
		var inoutItemType = oRecord.getData("inoutItemType");
		var money = oData;
		if (!money || money == "null") {
			elCell.innerHTML = "";
		} else {
			if(inoutItemType == "0"){//支出
				elCell.innerHTML = "￥" + "<font color='#FF0000'>" + money + "</font>";
			}else if(inoutItemType == "1"){//收入
				elCell.innerHTML = "￥" + "<font color='#0000FF'>" + money + "</font>";
			}else if(inoutItemType == "2"){//存取款
				elCell.innerHTML = "￥" + "<font color='#00FF00'>" + money + "</font>";
			}else if(inoutItemType == "3"){//转账
				elCell.innerHTML = "￥" + "<font color='#00FF00'>" + money + "</font>";
			}else{//默认
				elCell.innerHTML = "￥" + money;
			}
		}
	}

	/**
	 * 下面是表格的设置
	 */
	var myColumnDefs = [ {
		key : "id",
		label : "ID",
		hidden : true
	}, {
		key : "inoutItemType",
		label : "收支项目类型",
		hidden : true
	}, {
		key : "no",
		label : "序号",
		minWidth : "25",
		resizeable : true
	}, {
		key : "dealDate",
		label : "交易日期",
		formatter : YAHOO.widget.DataTable.formatDate,
		sortable : true,
		minWidth : "68"
	}, {
		key : "inAccountName",
		label : "流入账户",
		sortable : true,
		minWidth : "70",
		resizeable : true
	}, {
		key : "outAccountName",
		label : "流出账户",
		sortable : true,
		minWidth : "70",
		resizeable : true
	}, {
		key : "inoutItemName",
		label : "收支项目",
		sortable : true,
		minWidth : "60",
		resizeable : true
	}, {
		key : "money",
		label : "金额",
		formatter : formatMoney,
		minWidth : "60",
		resizeable : true
	},{
		key : "moneyType",
		label : "币种",
		minWidth : "40",
		resizeable : true
	}, {
		key : "memo",
		label : "备注",
		minWidth : "160",
		resizeable : true
	}, {
		key : "relationUserName",
		label : "关联人",
		resizeable : true,
		minWidth : "80"
	}, {
		key : "logUserName",
		label : "记账人",
		resizeable : true,
		minWidth : "80"
	}, {
		key : "inAccountId",
		label : "流入账户ID",
		hidden : true
	}, {
		key : "outAccountId",
		label : "流出账户ID",
		hidden : true
	}, {
		key : "inoutItemId",
		label : "收支项目ID",
		hidden : true
	}, {
		key : "relationUserId",
		label : "关联人ID",
		hidden : true
	} ];

//	var myData = {'success':'true','resultSet':{'records':[{"id":"c373ff9d-b290-49c3-83bd-87826d732dd3","no":"1","dealDate":"2009-10-28","inoutItemId":"500","inoutItemName":"工资","inoutItemType":"1","inAccountId":"2","inAccountName":"某银行账户","outAccountId":"","outAccountName":"","money":"1000.00","moneyType":"人民币","memo":"","relationUserId":"000000","relationUserName":"eagle","logUserName":"超级管理员"}]}};
//	var myDataSource = new YAHOO.util.DataSource(myData); 
	var myDataSource = new YAHOO.util.DataSource(webRoot + "/hcm/tally/get");
	myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
	myDataSource.connXhrMode = "queueRequests";
	myDataSource.responseSchema = {
		resultsList : "resultSet.records",
		fields : [ "id", "no", "dealDate", "inoutItemId", "inoutItemName",
				"inoutItemType", "outAccountId", "outAccountName",
				"inAccountId", "inAccountName", "money", "moneyType", "memo",
				"relationUserId", "relationUserName", "logUserName" ]
	};
	
	YAHOO.hcm.tally.myDataTable = new YAHOO.widget.ScrollingDataTable("grid",
			myColumnDefs, myDataSource, {
				selectionMode : "single",
				width : "80em",
				height : "26.5em"
			});

	var inDialog = new InDialog();// 初始化收入对话框
	var outDialog = new OutDialog();// 初始化支出对话框

	var onRowClick = function(event, target) {
		YAHOO.hcm.tally.myDataTable.onEventSelectRow(event, target);
	}

	var onRowDbClick = function(event, target) {
		var elTarget = YAHOO.util.Event.getTarget(event);
		var record = YAHOO.hcm.tally.myDataTable.getRecord(elTarget);

		var inoutItemType = record.getData("inoutItemType");
		if (inoutItemType == '1') {// 收入
			inDialog.showDialog('update', record);
		} else if (inoutItemType == '0') {// 支出
			outDialog.showDialog('update', record);
		}
	}

	// 定义表行的单击事件
	YAHOO.hcm.tally.myDataTable.subscribe("rowClickEvent", onRowClick);
	// 定义表行的双击事件
	YAHOO.hcm.tally.myDataTable.subscribe("rowDblclickEvent", onRowDbClick);
	// Programmatically select the first row
	YAHOO.hcm.tally.myDataTable.selectRow(YAHOO.hcm.tally.myDataTable
			.getTrEl(0));

	// 定义“收入”按钮的点击事件监听函数
	YAHOO.util.Event.addListener("btn_in", "click", inDialog.showDialog,
			YAHOO.hcm.tally.dialog_in, true);

	// 定义“收入”按钮的点击事件监听函数
	YAHOO.util.Event.addListener("btn_out", "click", outDialog.showDialog,
			YAHOO.hcm.tally.dialog_out, true);
}

// 验证输入的金额是否合法
function moneyOnblur(moneyId,checkId) {
	var money = Dom.get(moneyId).value;
	var isDigit = Assistant.tools.isDigit(money);
	if (isDigit == false) {
		Dom.get(checkId).innerHTML = "金额非法";
	} else {
		Dom.get(checkId).innerHTML = "";
	}
}

/**
 * “收入”对话框
 * 
 * @return
 */
function InDialog() {
	var row = {};// 用于保存Grid中的表行数据
	var inoutItemType = 1;//0:支出；1:收入；2:存取款；3:转账
	/**
	 * 对话框的初始化函数
	 * 
	 * @param flag，如果为'update'，则说明该对话框用于修改数据；否则说明该对话框用于新增数据
	 * @param record，flag为'update'时，将要修改的数据
	 * @return
	 */
	var init = function(flag, record) {
		if (flag == 'update') {
			var id = record.getData("id");
			var dealDate = record.getData("dealDate");
			var inoutItemId = record.getData("inoutItemId");
			var inMoney = record.getData("money");
			var inAccountId = record.getData("inAccountId");
			var relationUserId = record.getData("relationUserId");
			var memo = record.getData("memo");

			Dom.get("in_id").value = id;
			Dom.get("in_dealDate").value = dealDate;
			Dom.get("in_inoutItem").value = inoutItemId;
			Dom.get("in_money").value = inMoney;
			Dom.get("in_account").value = inAccountId;
			Dom.get("in_relationUser").value = relationUserId;
			Dom.get("in_memo").value = memo;

			Dom.get("in_title").innerHTML = "修改收入信息";

			row = {};
			row.id = id;
			row.no = record.getData("no");
			row.dealDate = dealDate;
			row.inoutItemId = inoutItemId;
			row.inoutItemName = Assistant.tools.getSelectedText("in_inoutItem");
			row.money = inMoney;
			row.moneyType = record.getData("moneyType");
			row.inAccountId = inAccountId;
			row.inAccountName = Assistant.tools.getSelectedText("in_account");
			row.relationUserId = relationUserId;
			row.relationUserName = Assistant.tools
					.getSelectedText("in_relationUser");
			row.memo = memo;
			row.relationUserId = record.getData("relationUserId");
			row.relationUserName = record.getData("relationUserName");
			row.logUserId = record.getData("logUserId");
			row.logUserName = record.getData("logUserName");
		} else {
			Dom.get("in_id").value = "-1";
			Dom.get("in_dealDate").value = "";
			Dom.get("in_inoutItem").value = "-1";
			Dom.get("in_money").value = "";
			Dom.get("in_account").value = "-1";
			Dom.get("in_relationUser").value = "-1";
			Dom.get("in_memo").value = "";

			Dom.get("in_title").innerHTML = "新增收入";

			row = {};
		}
	}

	// Define various event handlers for Dialog
	var handleSave = function() {
		var ret = this.submit();
		if (ret) {
			this.hide();
		}
	};
	var handleSaveAndContinue = function() {
		YAHOO.hcm.tally.dialog_in.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	var handleSuccess = function(o) {
		var resultData = new ResultData(o);
		var flag = resultData.getUserData("flag");

		row.id = resultData.getUserData("id");
		row.dealDate = Dom.get("in_dealDate").value;
		row.inoutItemId = Dom.get("in_inoutItem").value;
		row.inoutItemName = Assistant.tools.getSelectedText("in_inoutItem");
		row.inoutItemType = inoutItemType;//收支项目的类型
		row.money = Dom.get("in_money").value;
		row.moneyType = resultData.getUserData("moneyType");
		row.inAccountId = Dom.get("in_account").value;
		row.inAccountName = Assistant.tools.getSelectedText("in_account");
		row.relationUserId = Dom.get("in_relationUser").value;
		row.relationUserName = Assistant.tools
				.getSelectedText("in_relationUser");
		row.memo = Dom.get("in_memo").value;
		row.logUserId = resultData.getUserData("logUserId");
		row.logUserName = resultData.getUserData("logUserName");

		if (resultData.isSuccess()) {
			if (flag == 'insert') {
				YAHOO.hcm.tally.myDataTable.addRow(row);
			}
			if (flag == 'update') {
				var selectedTrEls = YAHOO.hcm.tally.myDataTable
						.getSelectedTrEls();
				YAHOO.hcm.tally.myDataTable.updateRow(selectedTrEls[0], row);
			}
		} else {
			alert("保存失败，请重试！");
		}
		
		Dom.get("in_id").value = "-1";
		Dom.get("in_money").value = "";
		Dom.get("in_memo").value = "";
	};
	var handleFailure = function(o) {
		alert("保存失败：" + o.status);
	};

	// Instantiate the Dialog
	YAHOO.hcm.tally.dialog_in = new YAHOO.widget.Dialog("dialog_in", {
		width : "30em",
		fixedcenter : true,
		visible : false,
		constraintoviewport : true,
		hideaftersubmit : false,
		modal : true,
		buttons : [ {
			text : "保存并退出",
			handler : handleSave,
			isDefault : true
		}, {
			text : "保存并继续",
			handler : handleSaveAndContinue
		}, {
			text : "取消",
			handler : handleCancel
		} ]
	});

	// Validate the entries in the form to require that both first and last name
	// are entered
	YAHOO.hcm.tally.dialog_in.validate = function() {
		var data = this.getData();

		if (data.in_dealDate == "") {
			alert("请输入交易日期");
			return false;
		} else if (data.in_dealDate.length != 10) {
			alert("交易日期的格式不正确");
			return false;
		} else if (data.in_inoutItem == "-1") {
			alert("请选择收支项目");
			return false;
		} else if (data.in_money == "" || data.in_money == 0) {
			alert("请输入收入金额");
			return false;
		} else if (!Assistant.tools.isDigit(data.in_money)) {
			alert("金额非法");
			return false;
		} else if (data.in_account == "-1") {
			alert("请选择收入账户");
			return false;
		} else if (data.in_relationUser == "-1") {
			alert("请选择关联人员");
			return false;
		} else if (data.in_memo.length > 25) {
			alert("备注字数太多");
			return false;
		} else {
			return true;
		}
	};

	// Wire up the success and failure handlers
	YAHOO.hcm.tally.dialog_in.callback = {
		success : handleSuccess,
		failure : handleFailure
	};

	// Render the Dialog
	YAHOO.hcm.tally.dialog_in.render();

	var initInoutItem = false, initAccount = false, initRelationUser = false;

	this.showDialog = function(flag, record) {
		if (!initInoutItem) {
			init_inoutItem('in_inoutItem', '1');
			initInoutItem = true;
		}
		if (!initAccount) {
			init_account('in_account', 'a');
			initAccount = true;
		}
		if (!initRelationUser) {
			init_relationUser('in_relationUser');
			initRelationUser = true;
		}

		init(flag, record);

		// Render the Dialog
		Dom.get("dialog_in").style.display = "";
		YAHOO.hcm.tally.dialog_in.show();
	}
}

/**
 * “支出”对话框
 * 
 * @return
 */
function OutDialog() {
	var row = {};// 用于保存Grid中的表行数据
	var inoutItemType = 0;//0:支出；1:收入；2:存取款；3:转账
	/**
	 * 对话框的初始化函数
	 * 
	 * @param flag，如果为'update'，则说明该对话框用于修改数据；否则说明该对话框用于新增数据
	 * @param record，flag为'update'时，将要修改的数据
	 * @return
	 */
	var init = function(flag, record) {
		if (flag == 'update') {
			var id = record.getData("id");
			var dealDate = record.getData("dealDate");
			var inoutItemId = record.getData("inoutItemId");
			var outMoney = record.getData("money");
			var outAccountId = record.getData("outAccountId");
			var relationUserId = record.getData("relationUserId");
			var memo = record.getData("memo");

			Dom.get("out_id").value = id;
			Dom.get("out_dealDate").value = dealDate;
			Dom.get("out_inoutItem").value = inoutItemId;
			Dom.get("out_money").value = outMoney;
			Dom.get("out_account").value = outAccountId;
			Dom.get("out_relationUser").value = relationUserId;
			Dom.get("out_memo").value = memo;

			Dom.get("out_title").innerHTML = "修改支出信息";

			row = {};
			row.id = id;
			row.no = record.getData("no");
			row.dealDate = dealDate;
			row.inoutItemId = inoutItemId;
			row.inoutItemName = Assistant.tools.getSelectedText("out_inoutItem");
			row.money = outMoney;
			row.moneyType = record.getData("moneyType");
			row.outAccountId = outAccountId;
			row.outAccountName = Assistant.tools.getSelectedText("out_account");
			row.relationUserId = relationUserId;
			row.relationUserName = Assistant.tools
					.getSelectedText("out_relationUser");
			row.memo = memo;
			row.relationUserId = record.getData("relationUserId");
			row.relationUserName = record.getData("relationUserName");
			row.logUserId = record.getData("logUserId");
			row.logUserName = record.getData("logUserName");
		} else {
			Dom.get("out_id").value = "-1";
			Dom.get("out_dealDate").value = "";
			Dom.get("out_inoutItem").value = "-1";
			Dom.get("out_money").value = "";
			Dom.get("out_account").value = "-1";
			Dom.get("out_relationUser").value = "-1";
			Dom.get("out_memo").value = "";

			Dom.get("out_title").innerHTML = "新增支出";

			row = {};
		}
	}

	// Define various event handlers for Dialog
	var handleSave = function() {
		var ret = this.submit();
		if (ret) {
			this.hide();
		}
	};
	var handleSaveAndContinue = function() {
		YAHOO.hcm.tally.dialog_out.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	var handleSuccess = function(o) {
		var resultData = new ResultData(o);
		var flag = resultData.getUserData("flag");

		row.id = resultData.getUserData("id");
		row.dealDate = Dom.get("out_dealDate").value;
		row.inoutItemId = Dom.get("out_inoutItem").value;
		row.inoutItemName = Assistant.tools.getSelectedText("out_inoutItem");
		row.inoutItemType = inoutItemType;//收支项目的类型
		row.money = Dom.get("out_money").value;
		row.outAccountId = Dom.get("out_account").value;
		row.outAccountName = Assistant.tools.getSelectedText("out_account");
		row.relationUserId = Dom.get("out_relationUser").value;
		row.relationUserName = Assistant.tools
				.getSelectedText("out_relationUser");
		row.memo = Dom.get("out_memo").value;

		if (resultData.isSuccess()) {
			if (flag == 'insert') {
				YAHOO.hcm.tally.myDataTable.addRow(row);
			}
			if (flag == 'update') {
				var selectedTrEls = YAHOO.hcm.tally.myDataTable
						.getSelectedTrEls();
				YAHOO.hcm.tally.myDataTable.updateRow(selectedTrEls[0], row);
			}
		} else {
			alert("保存失败，请重试！");
		}
		
		Dom.get("out_id").value = "-1";
		Dom.get("out_money").value = "";
		Dom.get("out_memo").value = "";
	};
	var handleFailure = function(o) {
		alert("保存失败：" + o.status);
	};

	// Instantiate the Dialog
	YAHOO.hcm.tally.dialog_out = new YAHOO.widget.Dialog("dialog_out", {
		width : "30em",
		fixedcenter : true,
		visible : false,
		constraintoviewport : true,
		hideaftersubmit : false,
		modal : true,
		buttons : [ {
			text : "保存并退出",
			handler : handleSave,
			isDefault : true
		}, {
			text : "保存并继续",
			handler : handleSaveAndContinue
		}, {
			text : "取消",
			handler : handleCancel
		} ]
	});

	// Validate the entries in the form to require that both first and last name
	// are entered
	YAHOO.hcm.tally.dialog_out.validate = function() {
		var data = this.getData();

		if (data.out_dealDate == "") {
			alert("请输入交易日期");
			return false;
		} else if (data.out_dealDate.length != 10) {
			alert("交易日期的格式不正确");
			return false;
		} else if (data.out_inoutItem == "-1") {
			alert("请选择收支项目");
			return false;
		} else if (data.out_money == "" || data.out_money == 0) {
			alert("请输入支出金额");
			return false;
		} else if (!Assistant.tools.isDigit(data.out_money)) {
			alert("金额非法");
			return false;
		} else if (data.out_account == "-1") {
			alert("请选择支出账户");
			return false;
		} else if (data.out_relationUser == "-1") {
			alert("请选择关联人员");
			return false;
		} else if (data.out_memo.length > 25) {
			alert("备注字数太多");
			return false;
		} else {
			return true;
		}
	};

	// Wire up the success and failure handlers
	YAHOO.hcm.tally.dialog_out.callback = {
		success : handleSuccess,
		failure : handleFailure
	};

	// Render the Dialog
	YAHOO.hcm.tally.dialog_out.render();

	var initInoutItem = false, initAccount = false, initRelationUser = false;

	this.showDialog = function(flag, record) {
		if (!initInoutItem) {
			init_inoutItem('out_inoutItem', '0');
			initInoutItem = true;
		}
		if (!initAccount) {
			init_account('out_account', 'a');
			initAccount = true;
		}
		if (!initRelationUser) {
			init_relationUser('out_relationUser');
			initRelationUser = true;
		}

		init(flag, record);

		// Render the Dialog
		Dom.get("dialog_out").style.display = "";
		YAHOO.hcm.tally.dialog_out.show();
	}
}

/**
 * “存取款”对话框
 * 
 * @return
 */
function AccessDialog() {
	
}

/**
 * 初始化收支项目
 * 
 * @param selectId，select组件的ID
 * @param type，项目类型。0：代表支出项目；1：代表收入项目
 * @return
 */
function init_inoutItem(selectId, type) {
	var url = '';
	var fontColor = '#0000FF';
	if (type == '0') {
		url = webRoot + "/hcm/inoutItem/getOutItems";
		fontColor = '#FF0000';
	} else if (type = '1') {
		url = webRoot + "/hcm/inoutItem/getInItems";
		fontColor = '#0000FF';
	}
	var oCallback = {
		success : function(oResponse) {
			var resultData = new ResultData(oResponse);
			var datas = resultData.getData();

			var select = YAHOO.util.Dom.get(selectId);

			for ( var i = 0; i < datas.length; i++) {
				var data = datas[i];

				if (data.leaf == false) {
					var option = new Option(data.name, data.id);
					option.style.color = fontColor;
					select.options.add(option);

					var optgroup = document.createElement('optgroup');
					optgroup.label = "(" + data.name + "下的子项目)";
					optgroup.style.color = "gray";
					select.appendChild(optgroup);

					for ( var j = 0; j < data.children.length; j++) {
						var child = data.children[j];
						var option = new Option(child.name, child.id);
						option.style.color = fontColor;
						optgroup.appendChild(option);
					}
				} else {
					var option = new Option(data.name, data.id);
					option.style.color = fontColor;
					select.options.add(option);
				}
			}
		},
		failure : function(oResponse) {
			alert('加载收支项目时出错，请重试！');
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', url, oCallback, null);
}

/**
 * 初始化账户
 * 
 * @param selectId，select组件的ID
 * @param type，账户类型。a：代表现金、银行类账户；b：代表债权债务账户
 * @return
 */
function init_account(selectId, type) {
	var url = '';
	if (type == 'a') {
		url = webRoot + "/hcm/account/getCashAndBankAccounts";
	} else if (type = 'b') {
		url = webRoot + "";
	}
	var oCallback = {
		success : function(oResponse) {
			var resultData = new ResultData(oResponse);
			var datas = resultData.getData();

			var select = YAHOO.util.Dom.get(selectId);

			for ( var i = 0; i < datas.length; i++) {
				var data = datas[i];

				var option = new Option(data.name, data.id);
				select.options.add(option);
			}
		},
		failure : function(oResponse) {
			alert('加载账户信息时出错，请重试！');
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', url, oCallback, null);
}

/**
 * 初始化关联用户
 * 
 * @param selectId，select组件的ID
 * @return
 */
function init_relationUser(selectId) {
	var url = webRoot + "/hcm/user/getRelationUser";
	var oCallback = {
		success : function(oResponse) {
			var resultData = new ResultData(oResponse);
			var datas = resultData.getData();

			var select = YAHOO.util.Dom.get(selectId);

			for ( var i = 0; i < datas.length; i++) {
				var data = datas[i];

				var option = new Option(data.name, data.id);
				if (data.currentUser != undefined && data.currentUser) {
					option.selected = true;
				}
				select.options.add(option);
			}
		},
		failure : function(oResponse) {
			alert('加载关联用户信息时出错，请重试！');
		}
	};
	YAHOO.util.Connect.asyncRequest('POST', url, oCallback, null);
}

YAHOO.util.Event.onDOMReady(init);
